package com.dommettj.rawfix.session;

import com.dommettj.rawfix.message.*;
import org.apache.log4j.Logger;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HeartbeatWorker implements MessageHandler {

    private static final Logger logger = Logger.getLogger(HeartbeatWorker.class);
    private final ScheduledExecutorService heartbeat = Executors.newScheduledThreadPool(1);
    private final MessageGenerator messageGenerator;
    private final Session session;
    private boolean beating = false;

    public HeartbeatWorker(final Session session, final MessageGenerator messageGenerator) {
        this.messageGenerator = messageGenerator;
        this.session = session;
    }

    public void stop() {
        heartbeat.shutdownNow();
        beating = false;
    }

    @Override
    public void handle(String message) {

        try {
            final MessageType messageType = MessageUtils.getMessageType(message);

            switch(messageType) {
                case LOGON:
                    handleLogon();
                    break;
                case HEARTBEAT:
                    handleHeartbeat();
                    break;
            }
        } catch (UnknownMessageTypeException e) {
            logger.error("Failed to handle message", e);
        }
    }

    private void handleLogon() {

        logger.debug("Logon message received. Starting heartbeats");

        //todo: beat at the rate specified in the logon message
        if(!beating) {
            heartbeat.scheduleAtFixedRate(new Runnable() {

                @Override
                public void run() {
                    try {
                        session.sendMessage(messageGenerator.createHeartbeatMessage());
                    } catch (SessionException e) {
                        logger.error("Failed to heartbeat", e);
                    }
                }
            }, 0, 30, TimeUnit.SECONDS);

            beating = true;
        } else {
            logger.warn("Already beating");
        }
    }

    private void handleHeartbeat() {

        logger.debug("Received heartbeat");
    }
}
